package sword_offer;

/**
 * @ClassName _36treeToDoublyList
 * @Description: TODO
 * @Author: yongliang.ma
 * @Create_time:2022/10/13 10:21
 */
public class _36treeToDoublyList {
    Node head, pre;// pre记录前一个遍历到的元素
    public Node treeToDoublyList(Node root) {
        if (root == null)
            return null;
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    }

    public void dfs(Node node){
        if (node == null)
            return;
        dfs(node.left);
        if (pre == null){
            head = node;
        }else{
            pre.right = node;
            node.left = pre;
        }
        pre = node;
        dfs(node.right);
    }

    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }
}
